from core.exceptions import CustomException
from fastapi import Request
import time
import hashlib
import hmac

# 密钥和固定参数
SECRET_KEY = "d0a0b2c3d4e5f601a8b9c0d1e2f30415"
CODE = "zztF1G0Z542"
VERSION = "v1"
MODULE = "INFERENCE"
TIMEOUT = 300  # 5分钟超时


def verify_auth(request: Request):
    """
    验证请求头中的参数和签名值
    """
    # 获取请求头参数
    content_type = request.headers.get("Content-Type")
    timestamp = request.headers.get("X-EBAPI-Timestamp")
    nounce = request.headers.get("X-EBAPI-Nounce")
    version = request.headers.get("X-EBAPI-Version")
    module = request.headers.get("x-ebapi-module")
    authorization = request.headers.get("Authorization")

    # 检查必需参数是否存在
    if not all([content_type, timestamp, nounce, version, module, authorization]):
        raise CustomException(code=400, message="Missing required headers")

    # 检查Content-Type是否为application/json
    if content_type != "application/json":
        raise CustomException(code=400, message="Invalid Content-Type")

    # 检查版本号是否为v1
    if version != VERSION:
        raise CustomException(code=400, message="Invalid version")

    # 检查模块是否为INFERENCE
    if module != MODULE:
        raise CustomException(code=400, message="Invalid module")

    # 解析Authorization
    if not authorization.startswith("EBAPI "):
        raise CustomException(code=401, message="Invalid Authorization format")
    auth_parts = authorization.split("EBAPI ")[1].split(":")
    if len(auth_parts) != 2:
        raise CustomException(code=401, message="Invalid Authorization format")
    code, signature = auth_parts

    # 检查code是否正确
    if code != CODE:
        raise CustomException(code=401, message="Invalid code")

    # 获取请求体内容
    body = request.body()
    # 计算请求体的MD5
    content_md5 = hashlib.md5(body).hexdigest().upper()
    
    # 生成签名字符串（匹配Java版本格式）
    path = request.url.path
    signature_string = f"POST:{path}:application/json:x-ebapi-module={MODULE};" \
                      f"x-ebapi-nounce={nounce};x-ebapi-timestamp={timestamp};" \
                      f"x-ebapi-version={VERSION}:{content_md5}::{timestamp}:{nounce}"

    # 生成签名值
    signature_bytes = signature_string.encode()
    secret_key_bytes = SECRET_KEY.encode()
    generated_signature = hmac.new(secret_key_bytes, signature_bytes, hashlib.sha256).hexdigest()

    # 比较签名值
    if generated_signature != signature:
        raise CustomException(code=401, message="Invalid signature")

    return True